package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    //跳转到login页面
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    //登录功能
    @RequestMapping("login")
    @ResponseBody
    public Result login(String username,String password){
        //1.创建subject对象
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户的账号密码 —> token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //3.执行登录功能,调用subject的login方法
        //shiro是通过抛异常的方式来提示账号不存在或者密码错误
        try {
            subject.login(token);
        }catch (UnknownAccountException u){
            return Result.response(ResultEnum.NOTID);
        }catch (IncorrectCredentialsException i){
            return Result.response(ResultEnum.PASSWORD_ERROR);
        }

        return Result.response(ResultEnum.SUCCESS);
    }
}
